#include <iostream>
#include "Thread.hpp"
#include <unistd.h>
#include <vector>

using namespace ThreadMoudle;

const int N = 20;

int ticketnum = 10;

int gap = 20;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;



// 模拟库

ThreadMoudle::Mutex gmtx;

class ThreadData
{
public:
    std::string _name;

    // pthread_mutex_t *lock_ptr;
};



void Ticket(ThreadData data)
{
    while(true)
    {
        gmtx.Lock();
        if(ticketnum > 0)
        {
            usleep(1000);
            
            std::cout<<"i am "<<data._name<<",i got ticket="<<ticketnum<<std::endl;
            ticketnum--;
            gmtx.Unlock();

            usleep(1000);
        }
        else 
        {
            pthread_cond_wait(&gcond,gmtx.Pmutex());
            gmtx.Unlock();
        }
            
    }
}


int main()
{
    std::vector<Thread<ThreadData>> threads;
    

    for(int i= 1; i<= N; ++i)
    {
        threads.emplace_back(Thread<ThreadData>(Ticket,{"thread-"+std::to_string(i)}));
    }
    for(auto& t : threads)
    t.Start();



    int cnt = 100;
    while(cnt--)
    {
        sleep(4);
        ticketnum += gap;
        std::cout<<"主线程放票了！！！ticketnum = "<<ticketnum<<std::endl;
        pthread_cond_signal(&gcond);

    }

    
    for(auto& t : threads)
    {
        std::cout<<"join "<<t.Name()<<" = "<<t.Join()<<std::endl;
    }

    return 0;
}


